package dao

import (
	"context"
	"gorm.io/gorm"
	"time"
)

type PackDao interface {
	Insert(ctx context.Context, pack Pack) error
	List(ctx context.Context, page, limit int) ([]Pack, int, error)
}

type packDao struct {
	db *gorm.DB
}

func NewPackDao(db *gorm.DB) PackDao {
	return &packDao{
		db: db,
	}
}

func (p *packDao) Insert(ctx context.Context, pack Pack) error {
	now := time.Now().UnixMilli()
	pack.CreateTime = now
	pack.UpdateTime = now
	return p.db.WithContext(ctx).Create(&pack).Error
}
func (f *packDao) List(ctx context.Context, page, limit int) ([]Pack, int, error) {
	var pack []Pack
	limit = limit
	offset := limit * (page - 1)

	var tatol int64
	db := f.db.Model(&Pack{}).WithContext(ctx)

	err := db.Count(&tatol).Error
	if err != nil {
		return pack, 0, err
	}
	err = db.Limit(limit).Offset(offset).Order("id desc").Find(&pack).Error
	return pack, int(tatol), err
}

type Pack struct {
	ID         int64 `gorm:"primaryKey;autoIncrement"`
	PackName   string
	Describe   string
	CreateTime int64
	UpdateTime int64
}
